package com.demo.juc;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.Test;

/**
 * 并发容器
 * @author HUZHAN150
 *
 */
public class ConCurrentHashMaptest {
	
	@Test
	public void test(){
		ExecutorService executor = Executors.newFixedThreadPool(100);
		final CounterDemo demo = new CounterDemo();
		int callTime = 10000;
		final String url = "http://www.importnew.com/26035.html";
		CountDownLatch latch = new CountDownLatch(callTime);
		for (int i = 0; i < callTime; i++) {
			executor.execute(new Runnable() {
				@Override
				public void run() {
					demo.increase2(url);
					latch.countDown();
				}
			});
		}
		
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		executor.shutdown();
		
		System.out.println(demo.getCount(url));
		
	}
}

class CounterDemo{
	private final Map<String, Long> urlCounter =  new ConcurrentHashMap<>();
	
	/**
	 * 
	 * @param url
	 * @return
	 */
	public long increase(String url){
		Long oldValue = urlCounter.get(url);
		Long newValue = (oldValue == null) ? 1L : oldValue + 1;
		urlCounter.put(url, newValue);
		return newValue;
	}
	
	public Long getCount(String url){
		return urlCounter.get(url);
	}
	
	/**
	 * 
	 * @param url
	 * @return
	 */
	public long increase2(String url){
		Long oldValue,newValue;
		while(true){
			oldValue = urlCounter.get(url);
			if (oldValue == null) {
				newValue = 1L;
				if (urlCounter.putIfAbsent(url, newValue) == null) {
					break;
				}
			}else {
				newValue = oldValue + 1;
				if (urlCounter.replace(url, oldValue, newValue)) {
					break;
				}
			}
		}
		return newValue;
	}
}
